
import { computed, ref } from 'vue'
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import dayjs from 'dayjs'
export function useObserver (apiFn) {
  const target = ref(null)
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      // console.log('我出现在可视区域了', isIntersecting)
      if (isIntersecting) {
        apiFn()
        // 当请求一次之后 停止监听防止二次请求
        stop()
      }
    }
  )
  return target
}

export function useCountDown (startCount) {
  const time = ref(0)
  // pause函数: 暂停定时器
  // 准备一个计算属性 基于原来的数字, 解析成xx分xx秒
  const countTimeTest = computed(() => {
    return dayjs.unix(time.value).format('mm分ss秒')
  })
  // resume函数: 开始定时器
  const { pause, resume } = useIntervalFn(() => {
    /* your function */
    if (time.value <= 0) {
      pause()
      return
    }
    time.value--
  }, 1000)
  // 封装一个初始化开始的方法
  const start = (startTime) => {
    time.value = startTime || startCount
    resume()
  }
  return {
    time,
    countTimeTest,
    start,
    pause,
    resume
  }
}
